package com.xh.demo.config.custom;

import com.xh.demo.common.annotation.MyRequestBody;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver;

import java.util.List;

/**
 * @Name MyRequesrBodyResolver
 * @Description 自定义的@MyRequesrBody注解的绑定实现类
 * @Author wen
 * @Date 2019-08-04
 */
public class MyRequesrBodyResolver extends AbstractMessageConverterMethodArgumentResolver {

    public MyRequesrBodyResolver(List<HttpMessageConverter<?>> converters) {
        super(converters);
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(MyRequestBody.class);//绑定注解
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        String token = webRequest.getHeader("token");
        //TODO Add BusinessException Logic
        //判断头部token是否存在
//        if (StringUtils.isEmpty(token)) {
//            throw new BusinessException(ErrorEnum.USER_TOKEN_IS_NOT_EXIST);
//        }
        //调用AbstractMessageConverterMethodArgumentResolver类中readWithMessageConverters方法
        return readWithMessageConverters(webRequest, parameter, parameter.getParameterType());
    }
}
